package cn.nexd.app.indoor.presenter;

import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.litesuits.orm.db.assit.QueryBuilder;
import com.litesuits.orm.db.model.ColumnsValue;
import com.litesuits.orm.db.model.ConflictAlgorithm;
import com.litesuits.orm.log.OrmLog;
import com.squareup.okhttp.Request;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import cn.nexd.app.indoor.Config;
import cn.nexd.app.indoor.R;
import cn.nexd.app.indoor.application.MyApplication;
import cn.nexd.app.indoor.model.FloorModel;
import cn.nexd.app.indoor.model.MallModel;
import cn.nexd.app.indoor.model.Mallconfig;
import cn.nexd.app.indoor.perimission.CheckPermission;
import cn.nexd.app.indoor.ui.activity.MallListActivity;
import cn.nexd.app.indoor.util.FileUtil;
import cn.nexd.app.indoor.util.LogUtil;
import cn.nexd.app.indoor.util.OkHttpClientManager;
import cn.nexd.app.indoor.util.ProgressDialogUtils;

/**
 * Created by wangxu on 16/7/19.
 */
public class MallListPresenter extends BasePresenter<MallListActivity> {

    private MallModel mallModel;
//    private DataBase dbOrm;

    public MallListPresenter(Context context, MallListActivity iView) {
        super(context, iView);
    }

    public void setMallModel(MallModel mallModel) {
        this.mallModel = mallModel;
    }

    public void checkIsExistRootFile() {
        iView.showProgress(View.VISIBLE, "小墨正在努力加载中......");
        if (!CheckPermission.checkPermission((Activity) context, "android.permission.READ_EXTERNAL_STORAGE")
                || !CheckPermission.checkPermission((Activity) context, "android.permission.WRITE_EXTERNAL_STORAGE")) {
            iView.showProgress(View.GONE, "");
            iView.showToast("存储权限被拒绝,请在设置中允许");
            return;
        }
        if (FileUtil.checkExist(Config.BASE_FILE_PATH + File.separator + mallModel.getMallId())) {
            checkUpdateFile();
        } else {
            downloadFile(mallModel.getUrl());
        }
    }

    public void requestFloor() {
        StringBuilder queryFloorUrl = new StringBuilder();
        queryFloorUrl.append("http://api.nexdtech.com/")
                .append("nexd/v1.0/getFloorsInfo.do");
//        ?appKey=f4b5aeaa1776f7af714e0663fa2e50b2")
//                .append("&buildingCode=")
//                .append(mallModel.getMallId());

        Map<String, String> param = new HashMap<>();
        param.put("appKey", "f4b5aeaa1776f7af714e0663fa2e50b2");
        param.put("buildingCode", mallModel.getMallId());
        iView.printLog("floorUrl", "queryFloorUrl = " + queryFloorUrl.toString(), LogUtil.DEBUG);
        OkHttpClientManager.postAsyn(queryFloorUrl.toString(), param, new OkHttpClientManager.ResultCallback<String>() {
            @Override
            public void onError(Request request, Exception e) {
                iView.showProgress(View.GONE, "");
                iView.printLog("requestFloor", e.getMessage(), LogUtil.ERROR);
                iView.showToast(context.getResources().getString(R.string.error_networkstatus_msg));
            }

            @Override
            public void onResponse(String response) {
                iView.printLog("floorResponse", "floorResponse = " + response, LogUtil.DEBUG);
                try {
                    JSONObject floorResult = new JSONObject(response);
                    if (floorResult.getBoolean("isSuccess")) {
                        JSONArray floorArray = floorResult.getJSONArray("floors");
                        ArrayList<FloorModel> floorModels = new ArrayList<>();

                        for (int i = 0; i < floorArray.length(); i++) {
                            FloorModel floorModel = new FloorModel();
                            JSONObject floorJson = floorArray.getJSONObject(i);
                            floorModel.setFloorId(floorJson.getString("floorId"));
                            floorModel.setFloorLayer(floorJson.getString("floorLayer"));
                            floorModel.setFloorName(floorJson.getString("floorName"));
                            floorModels.add(floorModel);
                        }
                        iView.intoNextActivity(mallModel, floorModels);
                        ProgressDialogUtils.dismissProgressDialog(context);
                        iView.printLog("MallList =======", mallModel.toString(), LogUtil.DEBUG);
                    } else {
                        ProgressDialogUtils.dismissProgressDialog(context);
                        iView.showToast(Config.getCodeMessage(floorResult.getString("msgCode")));
                    }
                } catch (JSONException e) {
                    iView.showProgress(View.GONE, "");
                    iView.showToast("数据异常");
                    MyApplication.getInstance().reportException(e);
                    e.printStackTrace();
                }
            }

        });
    }

    public void checkUpdateFile() {
        final ArrayList<Mallconfig> mallInfo = MyApplication.getLiteOrm().query(new QueryBuilder<>(Mallconfig.class)
                .where("mallID=?", new String[]{mallModel.getMallId()})
        );
        // 失败，获取下载地址，进行下载， 成功，直接load地图信息，执行页面跳转
        StringBuilder url = new StringBuilder();
        url.append(Config.BASE_REQUEST_URL);
        url.append("/v1.0/checkProp.do?buildingCode=");
        url.append(mallModel.getMallId());
        url.append("&md5=");
        if (mallInfo.size() == 0) {
            return;
        }
        url.append(mallInfo.get(0).getMd5());
        url.append("&appKey=f4b5aeaa1776f7af714e0663fa2e50b2");
        android.util.Log.d("checkUpdate", url.toString());
        OkHttpClientManager.postAsyn(url.toString(), "", new OkHttpClientManager.ResultCallback<String>() {
            @Override
            public void onError(Request request, Exception e) {
                iView.showProgress(View.GONE, "");
                iView.showToast(context.getResources().getString(R.string.error_networkstatus_msg));
            }

            @Override
            public void onResponse(String response) {
                try {
                    Log.d("downLoadSuccess", response);
                    iView.printLog("mallResponse", response, LogUtil.INFO);
                    JSONObject mallModelObject = new JSONObject(response);
                    if (mallModelObject.getBoolean("isSuccess")) {
                        if (mallModelObject.getString("msgCode").equals(Config.WEB_API_APP_NEED_UPDATE_PROP)) {
                            iView.printLog("checkUpdate", "需要更新", LogUtil.DEBUG);
                            mallModel.setMd5(mallModelObject.getString("md5"));
                            ColumnsValue columnMd5 = new ColumnsValue(new String[]{"md5"}, new String[]{mallModel.getMd5()});
                            MyApplication.getLiteOrm().update(mallInfo.get(0), columnMd5, ConflictAlgorithm.Replace);
                            OrmLog.d("md5update", "数据库更新了！");
                            downloadFile(mallModelObject.get("url").toString());
                            MyApplication.getLiteOrm().close();
                        } else {
                            iView.printLog("checkUpdate", "不需要更新!", LogUtil.DEBUG);
                            requestFloor();
                        }
                    } else {
                        iView.showProgress(View.GONE, "");
                        iView.showToast(Config.getCodeMessage(mallModelObject.getString("msgCode")));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    MyApplication.getInstance().reportException(e);
                }
            }
        });
    }


    public void downloadFile(String url) {
        iView.printLog("downloadFile", url, LogUtil.DEBUG);

        if (!TextUtils.isEmpty(url)) {
            OkHttpClientManager.getDownloadDelegate().downloadAsyn(url, Config.DOWNLOAD_FILE_PATH, new OkHttpClientManager.ResultCallback<String>() {
                @Override
                public void onError(Request request, Exception e) {
                    iView.showProgress(View.GONE, "");
                    e.printStackTrace();
//                    Log.d("download File error", request.body().toString());
                    iView.printLog("downLoadFile", e.getMessage(), LogUtil.ERROR);
                    iView.showToast(context.getResources().getString(R.string.error_networkstatus_msg));
                }

                @Override
                public void onResponse(String response) {
                    iView.printLog("response", "downloadFile = " + response, LogUtil.INFO);
                    String filePath = Config.DOWNLOAD_FILE_PATH + File.separator;
                    try {
                        FileUtil.unCompressZipFile(FileUtil.buildFile(response, false), filePath);
                        FileUtil.deleteFileOrDir(response);
                        String downloadFilePath = filePath + mallModel.getMallId();
                        // filePath ==> map_svg/download/10101001
                        FileUtil.shearFile(downloadFilePath, Config.BASE_FILE_PATH);
                        requestFloor();
                    } catch (IOException e) {
                        MyApplication.getInstance().reportException(e);
                    }
                }
            });
        }
    }
}
